﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace CPPEI.WebApi
{
    /// <summary>
    /// 存放认证信息（使用asp.net form认证）
    /// </summary>
    public class FormsAuthProvider : IAuthProvider
    {
        public bool Save(string userId, TimeSpan expires)
        {
            System.Web.Security.FormsAuthenticationTicket ticket = new System.Web.Security.FormsAuthenticationTicket(userId, true, (int)expires.TotalMinutes);
            //将票据加密 
            string authTicket = System.Web.Security.FormsAuthentication.Encrypt(ticket);
            //将加密后的票据保存为cookie 
            HttpCookie formCookie = new HttpCookie(System.Web.Security.FormsAuthentication.FormsCookieName, authTicket);
            formCookie.Expires = DateTime.Now.Add(expires);
            HttpResponse response = HttpContext.Current.Response;
            response.Cookies.Add(formCookie);

            //System.Web.Security.FormsAuthentication.SetAuthCookie(userId, true);
            return true;
        }

        public void Delete()
        {
            HttpRequest request = HttpContext.Current.Request;
            HttpResponse response = HttpContext.Current.Response;
            if (request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName] != null)
            {
                TimeSpan ts = new TimeSpan(-1, 0, 0, 0);
                request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName].Expires = DateTime.Now.Add(ts);//删除整个Cookie，只要把过期时间设置为现在
                response.AppendCookie(request.Cookies[System.Web.Security.FormsAuthentication.FormsCookieName]);
            }
            //System.Web.Security.FormsAuthentication.SignOut();
        }

        public string GetUserId()
        {
            if (HttpContext.Current.User == null
                || HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                return null;
            }
            return HttpContext.Current.User.Identity.Name;
        }

        public bool IsAuth()
        {
            if (HttpContext.Current.User == null
                || HttpContext.Current.User.Identity.IsAuthenticated == false)
            {
                return false;
            }
            return HttpContext.Current.User.Identity.IsAuthenticated;
        }
    }
}
